<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/3
 * Time: 14:09
 */

namespace app\common\util;

require_once(THINK_PATH . '../lib/phpqrcode/phpqrcode.php');

class QRCodeUtil
{
    private static function getFileName($filename)
    {
        $rt = TEMP_PATH . md5($filename) . '.png';
        $dir = dirname($rt);
        if (!file_exists($dir) || !is_dir($dir)) {
            mkdir($dir, 0666, true);
        }
        return $rt;
    }

    public static function png($value, $includeLogo = false)
    {
        //生成二维码图片
        $fileName = self::getFileName($value);
        $QR = $fileName;//已经生成的原始二维码图
        if (!file_exists($fileName) || !is_file($fileName)) {
            $errorCorrectionLevel = 'H';//容错级别
            $matrixPointSize = 6;//生成图片大小
            \QRcode::png($value, $fileName, $errorCorrectionLevel, $matrixPointSize, 2);
            $QR = imagecreatefromstring(file_get_contents($QR));
            if ($includeLogo) {
                $logo = __DIR__ . DIRECTORY_SEPARATOR . 'asset' . DIRECTORY_SEPARATOR . 'Icon-60@2x.png';//准备好的logo图片
                $logo = imagecreatefromstring(file_get_contents($logo));
                $QR_width = imagesx($QR);//二维码图片宽度
                //$QR_height = imagesy($QR);//二维码图片高度
                $logo_width = imagesx($logo);//logo图片宽度
                $logo_height = imagesy($logo);//logo图片高度
                $logo_qr_width = $QR_width / 5;
                $scale = $logo_width / $logo_qr_width;
                $logo_qr_height = $logo_height / $scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                //重新组合图片并调整大小
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                    $logo_qr_height, $logo_width, $logo_height);
            }
        }else{
            $QR = imagecreatefromstring(file_get_contents($QR));
        }
        //输出图片
//        ob_clean();
        header('Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header("content-type: image/png");
        // 输出图像
        imagepng($QR);
        imagedestroy($QR);
    }
}